package com.fulihui.wgj.schedule.job;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.common.util.SevenRemainingUtil;
import com.fulihui.wgj.facade.dto.WxPlatformDTO;
import com.fulihui.wgj.facade.request.retention.WxSevenRetentionRequest;
import com.fulihui.wgj.facade.service.platform.WxPlatformService;
import com.fulihui.wgj.facade.service.retention.WxSevenRetentionService;
import com.fulihui.wgj.facade.service.statistics.WxSubscribeStatisticsService;
import com.fulihui.wgj.schedule.annotation.MutexLock;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: LiuJie
 * @version: 2018/7/9 15:13
 * @description: 七日留存记录
 */
@Component
@Slf4j
public class SevenRemainingJob {
    @Autowired
    SevenRemainingUtil sevenRemainingUtil;
    @Reference(version = "1.0.0")
    WxPlatformService wxPlatformService;
    @Reference(version = "1.0.0")
    WxSevenRetentionService wxSevenRetentionService;
    @Reference(version = "1.0.0")
    WxSubscribeStatisticsService subscribeStatisticsService;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @MutexLock(node = "${job.node.seven_remaining_execute}")
    @Scheduled(cron = "${job.cron.seven_remaining_execute}")
    public void execute(){

        log.info("七日留存开始！");
        // 获取所有有效公众号
        List<WxPlatformDTO> platformList = wxPlatformService.queryUsefulPlatform().getData();
        if (CollectionUtils.isEmpty(platformList)) {
            log.info("platform list is empty, job over！");
            return;
        }
        log.info("七日留存 get 公众号信息！ appId:nickName={}", platformList.stream()
                .map(l -> l.getAppId() + ":" + l.getNickName())
                .collect(Collectors.toList()));
        // [-1,-8] ，-1 就是
        for(int i = -1 ;i >= -8 ; i--){
            Date queryDate = DateUtils.addDays(new Date(), i);
            // 每个公众号
            for (WxPlatformDTO platform : platformList) {
                // 获取当天流失人数
                Long incr = sevenRemainingUtil.countUnsubscribe(platform.getAppId(), queryDate.getTime());
                save(platform.getAppId(),queryDate,i,incr);
            }
        }
        log.info("七日留存结束！");
    }

    /**
     *
     * @param appid
     * @param queryDate
     * @param i |天数|
     * @param d 留存率
     */
    private void save(String appid,Date queryDate,int i,Long d){

        if(null == d){
            d = 0L;
        }
        WxSevenRetentionRequest request = new WxSevenRetentionRequest();
        request.setAppId(appid);
        request.setDate(sdf.format(queryDate));

        switch (i){
            case -1:
                request.setZeroDay(d.intValue());
                break;
            case -2:
                request.setOneDay(d.intValue());
                break;
            case -3:
                request.setTwoDay(d.intValue());
                break;
            case -4:
                request.setThreeDay(d.intValue());
                break;
            case -5:
                request.setFourDay(d.intValue());
                break;
            case -6:
                request.setFiveDay(d.intValue());
                break;
            case -7:
                request.setSixDay(d.intValue());
                break;
            case -8:
                request.setSevenDay(d.intValue());
                break;
            default:
        }
        BaseResult baseResult ;
        if (i == -1) {
            baseResult = wxSevenRetentionService.saveWxSevenRetention(request);
            log.info("七日留存入库request={}，result={}",request,baseResult);
        }else if(-8 <= i &&  i <= -2){
            baseResult = wxSevenRetentionService.updateByAppIdAndDate(request);
            log.info("七日留存更新request={}，result={}",request,baseResult);
        }else {
            log.error("参数有误，request = {}",request);
        }

    }

}
